package com.itheima.reggie.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itheima.reggie.constant.CommonConstant;
import com.itheima.reggie.util.LoginUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

/**
 * 自定义元数据对象处理器
 */
@Component
@Slf4j
public class MyMetaObjecthandler implements MetaObjectHandler {

    @Autowired
    private LoginUserUtil loginUserUtil;
    /**
     * 插入操作，自动填充
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]...");
        log.info(metaObject.toString());

        System.out.println();

        Object user = loginUserUtil.getBackendUser();
        if(user == null)
        {
            metaObject.setValue(CommonConstant.MYSQL_CREATEUSER,new Long(1));
            metaObject.setValue(CommonConstant.MYSQL_UPDATEUSER,new Long(1));
        }else{
            Long userLong = Long.parseLong(user.toString());
            metaObject.setValue(CommonConstant.MYSQL_CREATEUSER,userLong);
            metaObject.setValue(CommonConstant.MYSQL_UPDATEUSER,userLong);
        }
        LocalDateTime localDateTime = LocalDateTime.now();
        metaObject.setValue(CommonConstant.MYSQL_CREATETIME, localDateTime);
        metaObject.setValue(CommonConstant.MYSQL_UPDATETIME,localDateTime);

    }

    /**
     * 更新操作，自动填充
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]...");
        log.info(metaObject.toString());

        Object user = loginUserUtil.getBackendUser();
        if(user == null)
        {
            metaObject.setValue(CommonConstant.MYSQL_UPDATEUSER,new Long(1));
        }else{
            Long userLong = Long.parseLong(user.toString());
            metaObject.setValue(CommonConstant.MYSQL_UPDATEUSER,userLong);
        }

        metaObject.setValue(CommonConstant.MYSQL_UPDATETIME,LocalDateTime.now());

    }
}